import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  
  // 获取部署域名，用于代理配置
  const deployDomain = env.VITE_DEPLOY_DOMAIN || 'http://localhost'
  
  // 解析域名和端口
  const deployUrl = new URL(deployDomain)
  // 只有在非默认端口时才添加端口号
  const needsPort = deployUrl.port && 
    !((deployUrl.protocol === 'https:' && deployUrl.port === '443') || 
      (deployUrl.protocol === 'http:' && deployUrl.port === '80'))
  const proxyTarget = `${deployUrl.protocol}//${deployUrl.hostname}${needsPort ? ':' + deployUrl.port : ''}`
  
  return {
    plugins: [vue(), vueDevTools()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      proxy: {
        '/api': {
          target: env.VITE_API_BASE_URL?.startsWith('http') ? env.VITE_API_BASE_URL.replace('/api', '') : 'http://localhost:8125',
          changeOrigin: true,
          secure: false,
        },
        // 动态配置静态资源代理（仅开发环境需要）
          ...(mode === 'development' && deployDomain.includes('localhost') ? {
            '^/\\d+/code_output': {
              target: proxyTarget,
              changeOrigin: true,
              secure: false,
              rewrite: (path) => path
            },
            '^/\\d+/code_deploy': {
              target: proxyTarget,
              changeOrigin: true,
              secure: false,
              rewrite: (path) => path
            }
          } : {})
      },
    },
  }
})
